package com.calligraphy.product.web.controller;

import com.alibaba.fastjson.JSONObject;
import com.calligraphy.bases.utils.SetMsg;
import com.calligraphy.product.service.SeckillService;
import com.calligraphy.product.vo.SecKillInfoVO;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

/**
 * @Author hy
 * @Date 2019/1/10 14:45
 **/
@Slf4j
@RestController
@RequestMapping("/secKill")
public class SecKillController implements InitializingBean {

    @Autowired
    private SeckillService service;

    @Autowired
    private StringRedisTemplate redisTemplate;


    /**
     * 秒杀列表
     * @param
     * @return
     */
    @PostMapping("/list")
    public JSONObject list(){
        JSONObject json = new JSONObject();
        json.put("result",service.findSecKillList());
        SetMsg.setMessage(json,0,"success");
        return json;
    }

    @PostMapping("/detail")
    public JSONObject detail(@RequestParam("productId") String productId){
        JSONObject json = new JSONObject();
        SecKillInfoVO infoVO = service.findSecKillInfo(productId);

        long startAt = infoVO.getStartDate().getTime();
        long endAt = infoVO.getEndDate().getTime();
        long now = System.currentTimeMillis();
        // 秒杀状态.
        int seckillStatus = 0; //0:未开始 1: 进行中 2: 已结束
        // 秒杀未开始
        int remainSeconds = 0;
        // 秒杀未开始
        if(now < startAt ) {
            seckillStatus = 0;
            remainSeconds = (int)((startAt - now )/1000);
        }// 秒杀已结束
        else if(now > endAt){
            seckillStatus = 2;
            remainSeconds = -1;
        }// 秒杀进行中
        else {
            seckillStatus = 1;
            remainSeconds = 0;
        }
        json.put("secKillInfoVO",infoVO);
        json.put("secKillStatus",seckillStatus);
        json.put("remainSeconds",remainSeconds);
        SetMsg.setMessage(json,0,"success");
        return json;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
      /*  List<SecKillInfoVO> secKillInfoVOList = service.findSecKillList();
        if(secKillInfoVOList == null){
            return;
        }
        for (SecKillInfoVO secKill: secKillInfoVOList) {
            redisTemplate.opsForValue().set("1",secKill.getStockCount());
        }*/
    }
}
